package com.wefans.wefansapp.activity;

import java.io.InputStream;
import java.lang.reflect.Array;
import java.net.URL;
import java.util.ArrayList;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.StrictMode;
import android.support.v4.widget.DrawerLayout;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.wefans.wefansapp.R;
import com.wefans.wefansapp.common.tool.data.BenefitData;
import com.wefans.wefansapp.common.tool.data.BenefitDetailData;
import com.wefans.wefansapp.common.tool.data.BenefitDetailResponseData;
import com.wefans.wefansapp.common.tool.data.BenefitResponseData;
import com.wefans.wefansapp.common.tool.data.BenefitVoteData;
import com.wefans.wefansapp.common.tool.data.MFDataManager;
import com.wefans.wefansapp.common.tool.debug.MFDebug;
import com.wefans.wefansapp.common.tool.network.MFNetworkManager;
import com.wefans.wefansapp.common.tool.network.MFNetworkManager.IOnNetworkListener;
import com.wefans.wefansapp.common.tool.network.model.NetImage;
import com.wefans.wefansapp.common.tool.network.model.NetJsonData;
import com.wefans.wefansapp.common.tool.network.model.NetMessage;

public class BenefitDetailActivity extends BaseActivity implements IOnNetworkListener {

	private LinearLayout mSCreen = null;
    private DrawerLayout   m_DrawerLayout  = null;
    private FrameLayout    m_DrawerView    = null;
    private ImageView	   m_MainImage	   = null;
    private TextView	   m_CurrentUser   = null;
    private TextView	   m_Vote		   = null;
    private TextView	   m_Dday		   = null;
    private TextView	   m_Description1  = null;
    private TextView	   m_Description2  = null;
    private TextView	   m_DetailInfo1   = null;
    private TextView	   m_DetailInfo2   = null;
    private String		   m_event_idx 	   = null;
    private MFNetworkManager m_oNetworManager = null;
    private MFDataManager    m_oDataManager   = null;
    private Toast 			 toastVote = null;
    private BenefitDetailData m_benefitDetail = new BenefitDetailData();
    private BenefitVoteData mBenefitVoteDate = new BenefitVoteData();
    private ArrayList<BenefitDetailResponseData> m_benefitDetailResponse = new ArrayList<BenefitDetailResponseData>();

    Intent it;
    
    
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.activity_benefit_detail);
		StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork().penaltyLog().build());
		m_oNetworManager = MFNetworkManager.getInstance(this);
        m_oDataManager   = MFDataManager.getInstance(this);
		Intent prevIntent = getIntent();
		m_event_idx = prevIntent.getStringExtra("event_idx");
		initialize();
        installEvent();
		mSCreen = (LinearLayout)findViewById(R.id.LL_BENEFITDETAIL);
		setTitle("BenefitDetail");
		String bkColor = new String("#FEF2DC");
		mSCreen.setBackgroundColor(Color.parseColor(bkColor));
		
	}
	
	@Override
    public void onClick(View v)
    {
        MFDebug.d(">> onClick()");
        
        switch( v.getId() ) {
            case R.id.IB_BENEFIT_DETAIL_HEADER_LEFT_BUTTON :
                m_DrawerLayout.openDrawer(m_DrawerView);
                break;
            case R.id.TV_BENEFIT_DETAIL_QUICK_SEND :
    	        MFDebug.d("++ v.getId() : " + "TV_BENEFIT_DETAIL_QUICK_SEND");
    	        MFDataManager mem_idx = MFDataManager.getInstance(this);
    	        try{
    	        	m_oNetworManager.requestBenfitVote(mem_idx.getMebmerIdx(),m_event_idx,"1",this);
        	        //m_oNetworManager.requestBenfitVote("1","91","1",this);
    	        }catch (Exception e){
    	        	
    	        }
    			break;
            case R.id.TV_BENEFIT_DETAIL_SEND :
    	        MFDebug.d("++ v.getId() : " + "TV_BENEFIT_DETAIL_SEND");
				it = new Intent(getApplicationContext(), BenefitVoteActivity.class);
				it.putExtra("title",m_benefitDetailResponse.get(0).getBenefit_title());
				it.putExtra("event_idx",m_benefitDetailResponse.get(0).getIdx());
				startActivityForResult(it,v.getId());
				break;
            case R.id.TV_BENEFIT_DETAIL_RANK :
    	        MFDebug.d("++ v.getId() : " + "TV_BENEFIT_DETAIL_RANK");
				it = new Intent(getApplicationContext(), BenefitResultActivity.class);
				startActivityForResult(it,v.getId());
            default :
                break;
        }
        
        super.onClick(v);
    }
	
    private void initialize()
    {
        MFDebug.d(">> initialize()");
        
        //Contents layout adding
        FrameLayout containerContents = (FrameLayout) findViewById(R.id.FL_BENEFIT_DETAIL_CONTAINER);
        addContentsLayout(containerContents, R.layout.layout_benefit_detail);
        
        //Drawer menu adding
        m_DrawerView = (FrameLayout) findViewById(R.id.FL_BENEFIT_DETAIL_DRAWER_LAYOUT);
        addDrawerLayout(m_DrawerView);
        
        //set drawer layout (root)
        m_DrawerLayout = (DrawerLayout) findViewById(R.id.DL_BENEFIT_DETAIL_NAVIGATION_LAYOUT);
    }
    
    private void installEvent()
    {
        MFDebug.d(">> installEvent()");
        m_MainImage     = (ImageView) findViewById(R.id.IV_BENEFIT_IMG);
        m_Vote			= (TextView) findViewById(R.id.TV_BENEFIT_DETAIL_QUICK_SEND);
        m_Dday			= (TextView) findViewById(R.id.TV_DETAIL_DDAY);
        m_CurrentUser	= (TextView) findViewById(R.id.TV_BENEFIT_DETAIL);
        m_Description1 	= (TextView) findViewById(R.id.TV_BENEFIT_DETAILDESC1);
        m_Description2 	= (TextView) findViewById(R.id.TV_BENEFIT_DETAILDESC2);
        m_DetailInfo1 	= (TextView) findViewById(R.id.TV_BENEFIT_DETAIL_INFO1);
        m_DetailInfo2 	= (TextView) findViewById(R.id.TV_BENEFIT_DETAIL_INFO2);
        
        m_Vote.setText(this.getString(R.string.benefit_send));
        
//      if(msp.getMem_idx()==null){
      	RequestServerBenefitDetailData("1", m_event_idx);
//      }else{
//      	RequestServerBenefitData(msp.getMem_idx());
//      }
        
        //todo detail 정보 취득하여 입력하는 것으로 수정
        //서브타이틀은 데이터 파싱을 통해 구해 표시
//        m_Dday.setText("23D");
//        m_Description1.setText("2014 드림콘서트 ORANGE ZONE 초대권 2매");
//        m_Description2.setText("(2014.05.12~2014.05.12)");
//        m_DetailInfo1.setText("응모횟수: \n당첨기준: \n당첨발표: ");
//        m_DetailInfo2.setText("제한없음\n추첨 10000명\n2014.05.12");
//        m_CurrentUser.setText("나의응모 : 3 | 응모자 : 356485");
        
        
		
        ((ImageButton) findViewById(R.id.IB_BENEFIT_DETAIL_HEADER_LEFT_BUTTON)).setOnClickListener(this);
        findViewById(R.id.TV_BENEFIT_DETAIL_QUICK_SEND).setOnClickListener(this);
		findViewById(R.id.TV_BENEFIT_DETAIL_SEND).setOnClickListener(this);
		findViewById(R.id.TV_BENEFIT_DETAIL_RANK).setOnClickListener(this);
        
    }
    
	private void RequestServerBenefitDetailData(String mem_idx, String event_idx){
		 m_oNetworManager.requestBenfitDetail(mem_idx, event_idx, this);	
	}
	
	private Drawable LoadImageFromWebURL(String url){
		try{
			InputStream is = (InputStream) new URL(url).getContent();
			Drawable d = Drawable.createFromStream(is,"src name");
			return d;
		}catch (Exception e){
			MFDebug.d(">> LoadImageFromWebURL() error: " + e);
			return null;
		}
	}

	@Override
	public void onNetMessage(int resultCode, NetMessage message) {
        MFDebug.d(">> onNetMessage()");
        MFDebug.d("++ resultCode : " + resultCode);
        MFDebug.d("++ message : " + message);
        
        try {
            //서버 여동 데이터
            if( message instanceof NetJsonData ) {
                long magicNum = ((NetJsonData) message).getMagicNum();
                String json = ((NetJsonData) message).getResponseJson();
                
                if( json == null ) {
                    throw new Exception("invalid json data");
                }
                
                Gson gson = new Gson();
                
                if( magicNum == MFNetworkManager.REQUEST_BENEFIT_DETAIL ) {
                	m_benefitDetail = (BenefitDetailData)gson.fromJson(json, BenefitDetailData.class);
                    if( m_benefitDetail == null ) {
                        throw new Exception("Gson parsing error");
                    }
                    
                    m_oDataManager.setBenefitDetailData(m_benefitDetail);
                    m_benefitDetailResponse = (ArrayList<BenefitDetailResponseData>) m_benefitDetail.getData().clone();
                    m_MainImage.setImageDrawable(LoadImageFromWebURL(m_benefitDetailResponse.get(0).getImg_url()));
                    m_Dday.setText(m_benefitDetailResponse.get(0).getD_day()+"D");
                    m_Description1.setText(m_benefitDetailResponse.get(0).getTitle());
                    m_Description2.setText(m_benefitDetailResponse.get(0).getStart_date()+"~"+m_benefitDetailResponse.get(0).getEnd_date());
                    m_DetailInfo1.setText(getString(R.string.benefit_vote_cnt)+": \n"+ getString(R.string.benefit_result_rule)+": \n"+ 
                    						getString(R.string.benefit_result_action) +": ");
                    m_DetailInfo2.setText(getString(R.string.benefit_unlimited)+"\n"+getString(R.string.benefit_people_rule) +
                    						"10000"+getString(R.string.benefit_people_cnt)+"\n"+ m_benefitDetailResponse.get(0).getPub_date());
                    m_CurrentUser.setText(getString(R.string.benefit_cnt)+ " : " + m_benefitDetailResponse.get(0).getMy_cnt() + " | " +
											getString(R.string.benefit_vote_cnt) + " : " + m_benefitDetailResponse.get(0).getTot_mem_cnt());
                } else if( magicNum == MFNetworkManager.REQUEST_BENEFIT_VOTE ) {
                	mBenefitVoteDate = (BenefitVoteData)gson.fromJson(json, BenefitVoteData.class);
                    if( mBenefitVoteDate == null ) {
                        throw new Exception("Gson parsing error");
                    }
                    if( mBenefitVoteDate.getResultcode().equals("1") ){
                    	toastVote = Toast.makeText(this, getString(R.string.benefit_vote_success), Toast.LENGTH_LONG);
                    }else{
                    	toastVote = Toast.makeText(this, mBenefitVoteDate.getErrorcode() + ":" + getString(R.string.benefit_vote_fail), Toast.LENGTH_LONG);
                    }
                    toastVote.show();
                }
            }
            //이미지 데이터
            else if( message instanceof NetImage ) {
                
            }
            else {
                //ignore...
            }
        } catch(Exception e) {
            MFDebug.e(e);
        }
    }
}